package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.ItemComment;
import com.leyou.trade.entity.Order;
import com.leyou.trade.enums.OrderStatus;
import com.leyou.trade.mapper.ItemCommentMapper;
import com.leyou.trade.service.ItemCommentService;
import com.leyou.trade.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ItemCommentServiceImpl extends ServiceImpl<ItemCommentMapper, ItemComment> implements ItemCommentService {

    private final OrderService orderService;

    public ItemCommentServiceImpl(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 对订单进行评价
     * @param comment
     * @return
     */
    @Transactional
    @Override
    public Boolean comment(ItemComment comment) {
        Long userId = UserContext.getUser().getId();
        //1.查询当前订单的状态, 务必将订单号与userId进行双重效验。
        Order order = orderService.getOne(new QueryWrapper<Order>().select("status").eq("order_id", comment.getOrderId()).eq("user_id",userId));
        boolean success = order.getStatus() == OrderStatus.CONFIRMED.getValue();
        //2.如果当前订单状态不是confirmed就抛出异常
        Assert.isTrue(success, "当前订单状态不能商品评价!");

        String commentId = createCommentId(comment.getOrderId());
        comment.setUserId(userId);
        comment.setId(commentId);

        //3.保存用户评论信息，通过唯一主键做幂等性判断
        success = save(comment);
        //4.如果数据库保存失败抛出异常
        Assert.isTrue(success,"评论提交失败!");

        //5.更新订单状态，如果提交失败抛出异常
        success = orderService.update().set("status",OrderStatus.RATED.getValue()).eq("order_id",comment.getOrderId()).update();
        Assert.isTrue(success,"订单状态修改失败！");
        return success;
    }

    private String createCommentId(Long orderId) {
        String template = "U%dO%d";
        return String.format(template, UserContext.getUser().getId(), orderId);
    }

    @Override
    public ItemComment getComment(Long orderId) {
        return query().eq("order_id", orderId).one();
    }

    @Override
    public Boolean addComment(Long orderId,String afterComment) {
        return update().eq("order_id", orderId).eq("user_id",UserContext.getUser().getId()).set("after_comment", afterComment).update();
    }
}
